#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <md5.h>

int get_ip_broad_mask(int sockfd,struct in_addr* ip,struct in_addr* broad,struct in_addr* mask)
{
	struct ifreq buf[16] = {};
	struct ifconf ifc = {};
	ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = (caddr_t)buf;
    
    if(ioctl(sockfd, SIOCGIFCONF, (char *)&ifc))
    {
    	perror("ioctl");
    	return -1;
    }
    
    for(int i=0; i<ifc.ifc_len/sizeof(struct ifreq); i++)
    {
    	if(ioctl(sockfd, SIOCGIFADDR, (char *)&buf[i]))
        {
        	perror("ioctl ip addr");
        	return -1;
        }
        *ip = ((struct sockaddr_in *)&(buf[i].ifr_addr))->sin_addr;
        
        if(ioctl(sockfd, SIOCGIFBRDADDR, &buf[i]))
        {
           	perror("ioctl broad addr");
        	return -1;
        }
        
        *broad = ((struct sockaddr_in*)&(buf[i].ifr_broadaddr))->sin_addr;
        
       	if(ioctl(sockfd, SIOCGIFNETMASK, &buf[i]))
       	{
       		perror("ioctl mask addr");
        	return -1;
       	}
       	
       	*mask = ((struct sockaddr_in *)&(buf[i].ifr_netmask))->sin_addr;
       	if(*(int*)ip && *(int*)broad && *(int*)mask)
        {
        	return 0;
       	}
    }
}

//清理输入缓冲区
void clear_stdin(void)
{
	stdin->_IO_read_ptr = stdin->_IO_read_end;
}

//获取字符串
char* get_str(char* str,size_t size)
{
	clear_stdin();

	fgets(str,size,stdin);
	uint8_t len = strlen(str);

	if(str[len-1] == '\n') 
	{
		str[len-1] = '\0';
	}

	clear_stdin();
}

char* file_md5(const char* path,unsigned char* decrypt)
{
	
	FILE *fp = fopen(path,"rb");
	if(fp == NULL) 
	{
		perror("fopen");
		return NULL;
	}
	
	MD5_CTX md5;	
	MD5Init(&md5);
	unsigned char encrypt[1024];
	while(!feof(fp)) 
	{
		MD5Update(&md5, encrypt, fread(encrypt, 1, sizeof(encrypt), fp));
	}
	fclose(fp);
			
	MD5Final(&md5, decrypt);

	return decrypt;
}
